<?php
namespace App\Api\Controllers\CmbcUnion;


use App\Api\Controllers\DuoLaBao\WxBaseController;
use App\Models\MemberList;
use App\Models\MemberSetJf;
use App\Models\MemberTpl;
use App\Models\Store;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WxOauthController extends WxBaseController
{

    //拼接链接获取
    public function oauth(Request $request)
    {
        $state = $this->decode($request->get('state'));
        $options = $this->Options($state['config_id']);
        $scope_type = $state['scope_type'];//snsapi_base snsapi_userinfo获取的信息不一样
        $sub_info = $request->get('state');
        $config = [
            'app_id' => $options['app_id'],
            'scope' => $scope_type,
            'oauth' => [
                'scopes' => [$scope_type],
                'response_type' => 'code',
                'callback' => url('/api/cmbcunion/weixin/callback?sub_info=' . $sub_info),
            ],
        ];

        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        return $oauth->redirect();
    }


    public function callback(Request $request)
    {
        $sub_info = $request->get('sub_info');
        $sub_info = $this->decode($sub_info);
        $options = $this->Options($sub_info['config_id']);
        $sub_info['code'] = $request->get('code');
        $users = $this->users($sub_info, $options);

        $store_id = $sub_info['store_id'];
        $store_name = $sub_info['store_name'];
        $merchant_id = $sub_info['merchant_id'];

        $data = [
            'store_id' => $store_id,
            'store_name' => $store_name,
            'store_address' => '',
            'open_id' => $users->token->openid,
            'merchant_id' => $merchant_id
        ];
        $data = base64_encode(json_encode((array)$data));
        $url = url('/api/cmbcunion/weixin/pay_view');
        header("Location: $url/?data=".$data);
    }


    //微信支付视图页面
    public function pay_view(Request $request)
    {
        $data = json_decode(base64_decode((string)$request->get('data')), true);

        return view('cmbcUnion.weixin', compact('data'));
    }


    //获取users
    public function users($sub_info, $options)
    {
        $code = $sub_info['code'];
        $config = [
            'app_id' => $options['app_id'],
            "secret" => $options['app_secret'],
            "code" => $code,
            "grant_type" => "authorization_code",
        ];
        $app = Factory::officialAccount($config);
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        return $user = $oauth->user();
    }


}
